package com.imu.purse.admin.controller.business;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.imu.purse.modules.app.entity.ImuUserEntity;
import com.imu.purse.modules.app.service.ImuUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.github.pagehelper.PageInfo;
import com.imu.common.annotation.SysLog;
import com.imu.common.utils.R;
import com.imu.common.validator.ValidatorUtils;
import com.imu.common.validator.group.AddGroup;
import com.imu.common.validator.group.UpdateGroup;
import com.imu.purse.modules.trade.entity.TradeInfoEntity;
import com.imu.purse.modules.trade.service.TradeInfoService;
import com.xiaoleilu.hutool.bean.BeanUtil;
import com.xiaoleilu.hutool.date.DateUtil;
import com.xiaoleilu.hutool.util.StrUtil;

/**
 * 交易表
 * @author sunhongwei
 * @email sunhongwei@jshijian.com
 * @date 2018-04-17 11:30:06
 * Copyright (c) 2017 武汉极时间科技有限公司 版权所有 
 * Jshijian aloha CO.,LTD. All Rights Reserved. 
 */
@RestController
@RequestMapping("tradeinfo")
public class TradeInfoController extends com.imu.purse.modules.sys.controller.AbstractController
{
	/****
	 * 查询交易表
	 * @param params
 	 * @date 2018-04-17 11:30:06
	 * @return
	 */
	@SysLog("查询交易表")
	@GetMapping("/list")
	@RequiresPermissions("tradeinfo:list")
	public R list(@RequestParam Map<String, Object> params)
	{
		R r = R.ok();
		if(CollectionUtils.isEmpty(params)) return r;
		
		TradeInfoEntity dto = BeanUtil.mapToBean(params, TradeInfoEntity.class, true);
		if(null == dto) return r;
		if(StrUtil.isBlank(dto.getP()) && StrUtil.isBlank(dto.getRecPhone()) && null == dto.getYtfType()) return r;
		
		if(null != dto && StrUtil.isBlank(dto.getSts()))
		{
			dto.setSts(DateUtil.beginOfYear(new Date()).toString());
		}
		if(null != dto && StrUtil.isBlank(dto.getEts()))
		{
			dto.setEts(DateUtil.endOfYear(new Date()).toString());
		}

		ImuUserEntity userEntity = null;
		if(!StrUtil.isEmpty(dto.getRecPhone())){
			String userStr = redisTemplate.opsForValue().get(dto.getRecPhone());
			if(!StrUtil.isEmpty(userStr)){
				userEntity = JSON.parseObject(userStr,ImuUserEntity.class);
				dto.setRecUserId(userEntity.getId());
			}
			if(StrUtil.isEmpty(userStr) && dto.getRecUserId() == null){
				//从数据库查询
				userEntity = imuUserService.queryByMobile(dto.getRecPhone());
				if(userEntity != null){
					dto.setRecUserId(userEntity.getId());
					redisTemplate.opsForValue().set(userEntity.getPhone(),JSON.toJSONString(userEntity));
				}
			}

		}
		List<TradeInfoEntity> dtos = service.queryLists(dto);
		if(CollectionUtils.isEmpty(dtos)) return r;
		return r.put("page", new PageInfo<TradeInfoEntity>(dtos));
	}
	
	 @SysLog("查询交易统计表")
	  @GetMapping("/tradeSummaryList")
	  @RequiresPermissions("tradeinfo:tradeSummaryList")
	  public R tradeSummaryList(@RequestParam Map<String, Object> params)
	  {
	    R r = R.ok();
	    if(CollectionUtils.isEmpty(params)) return r;
	    
	    TradeInfoEntity dto = BeanUtil.mapToBean(params, TradeInfoEntity.class, true);
	    if(null == dto) return r;
	    if(StrUtil.isBlank(dto.getP()) && StrUtil.isBlank(dto.getRecPhone()) && null == dto.getYtfType()) return r;
	    
	    if(null != dto && StrUtil.isBlank(dto.getSts()))
	    {
	      dto.setSts(DateUtil.beginOfYear(new Date()).toString());
	    }
	    if(null != dto && StrUtil.isBlank(dto.getEts()))
	    {
	      dto.setEts(DateUtil.endOfYear(new Date()).toString());
	    }

	    ImuUserEntity userEntity = null;
	    if(!StrUtil.isEmpty(dto.getRecPhone())){
	      String userStr = redisTemplate.opsForValue().get(dto.getRecPhone());
	      if(!StrUtil.isEmpty(userStr)){
	        userEntity = JSON.parseObject(userStr,ImuUserEntity.class);
	        dto.setRecUserId(userEntity.getId());
	      }
	      if(StrUtil.isEmpty(userStr) && dto.getRecUserId() == null){
	        //从数据库查询
	        userEntity = imuUserService.queryByMobile(dto.getRecPhone());
	        if(userEntity != null){
	          dto.setRecUserId(userEntity.getId());
	          redisTemplate.opsForValue().set(userEntity.getPhone(),JSON.toJSONString(userEntity));
	        }
	      }

	    }
	    List<TradeInfoEntity> dtos = service.tradeSummaryList(dto);
	    if(CollectionUtils.isEmpty(dtos)) return r;
	    return r.put("page", new PageInfo<TradeInfoEntity>(dtos));
	  }
	
	/****
	 * 导出交易表
	 * @param ids
 	 * @date 2018-04-17 11:30:06
	 * @return
	 */
	@SysLog("导出交易明细")
	@GetMapping("/exprot")
	@RequiresPermissions("tradeinfo:exprot")
	public R exprot(@RequestParam Map<String, Object> params, HttpServletResponse response)
	{
		R r = R.ok();
		if(CollectionUtils.isEmpty(params)) return r;
		
		TradeInfoEntity dto = BeanUtil.mapToBean(params, TradeInfoEntity.class, true);
		if(null == dto) return r;
		if(StrUtil.isBlank(dto.getP()) && StrUtil.isBlank(dto.getRecPhone()) && null == dto.getYtfType()) return r;
		
		if(null != dto && StrUtil.isBlank(dto.getSts()))
		{
			dto.setSts(DateUtil.beginOfYear(new Date()).toString());
		}
		if(null != dto && StrUtil.isBlank(dto.getEts()))
		{
			dto.setEts(DateUtil.endOfYear(new Date()).toString());
		}

		ImuUserEntity userEntity = null;
		if(!StrUtil.isEmpty(dto.getRecPhone())){
			String userStr = redisTemplate.opsForValue().get(dto.getRecPhone());
			if(!StrUtil.isEmpty(userStr)){
				userEntity = JSON.parseObject(userStr,ImuUserEntity.class);
				dto.setRecUserId(userEntity.getId());
			}
			if(StrUtil.isEmpty(userStr) && dto.getRecUserId() == null){
				//从数据库查询
				userEntity = imuUserService.queryByMobile(dto.getRecPhone());
				if(userEntity != null){
					dto.setRecUserId(userEntity.getId());
					redisTemplate.opsForValue().set(userEntity.getPhone(),JSON.toJSONString(userEntity));
				}
			}

		}
		
		service.export(response, dto);
		return null;
	}
	
	/****
	 * 根据ID查询交易表
	 * @param id
 	 * @date 2018-04-17 11:30:06
	 * @return
	 */
	@SysLog("根据ID查询交易表")
	@GetMapping("/info/{id}")
	@RequiresPermissions("tradeinfo:info")
	public R info(@PathVariable("id") Long id)
	{
		return R.ok().put("dto", service.findById(id));
	}
	
	/****
	 * 新增交易表
	 * @param dto
 	 * @date 2018-04-17 11:30:06
	 * @return
	 */
	@SysLog("新增交易表")
	@PostMapping("/save")
	@RequiresPermissions("tradeinfo:save")
	public R save(@RequestBody TradeInfoEntity dto)
	{
		ValidatorUtils.validateEntity(dto, AddGroup.class);
		//dto.setUserCreate(this.getUserId());
		//dto.setUserUpdate(this.getUserId());
		service.save(dto);
		return R.ok();
	}
	
	/****
	 * 修改交易表
	 * @param dto
 	 * @date 2018-04-17 11:30:06
	 * @return
	 */
	@SysLog("修改交易表")
	@PostMapping("/update")
	@RequiresPermissions("tradeinfo:update")
	public R update(@RequestBody TradeInfoEntity dto)
	{
		ValidatorUtils.validateEntity(dto, UpdateGroup.class);
		//dto.setUserUpdate(this.getUserId());
		service.update(dto);
		return R.ok();
	}
	
	/****
	 * 删除交易表
	 * @param ids
 	 * @date 2018-04-17 11:30:06
	 * @return
	 */
	@SysLog("删除交易表")
	@PutMapping("/delete")
	@RequiresPermissions("tradeinfo:delete")
	public R delete(@RequestBody String[] ids)
	{
		service.delete(ids);
		return R.ok();
	}
	
	@Autowired
	private TradeInfoService service;

	@Autowired
	private ImuUserService imuUserService;

	@Autowired
	private RedisTemplate<String,String> redisTemplate;

}